﻿using System;
using System.Collections.Generic;
using Data;
using LoginUI.Login;
using LoginUI.UI;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

namespace Login.Server
{
    public class ChooseServerPanel : BasePanel
    {
        // _serverRangeText 服务器范围(Text文本UI控件)
        public Text _serverRangeText;

        // 上次选择的服务器(Text文本UI控件)
        public Text _lastChooseServerText;

        // 服务器状态(Image图UI控件)
        public Image _lastServerStateImage;

        // 左侧服务器列表(ScrollView控件)
        public ScrollRect svLeft;

        // 右侧服务器列表(ScrollView控件)
        public ScrollRect svRight;

        // 服务器列表(ServerRightItem组件)
        private List<GameObject> _serverRightItems = new();
        private int segmentSize = 5;
        private List<ServerInfo> _serverData;
        private ValueTuple<int, int> _currentRangeTuple;
        private int loginId = -1;

        // 抽象方法(必须) 初始化
        public override void Init()
        {
            // 计算平均区间范围， serverData的数量模以 5，如果结果有余数，则加1
            var avgRange = _serverData.Count % segmentSize == 0 ? _serverData.Count / segmentSize : _serverData.Count / segmentSize + 1;
            var avgRangeList = IntervalSegmentation.SegmentInterval(_serverData.Count, segmentSize);
            for (var i = 0; i < avgRangeList.Count; i++)
            {
                var startIndex = avgRangeList[i].start; // i == 0 ? 1 : i * segmentSize + 1;
                var endIndex = avgRangeList[i].end; //i != avgRange - 1 ? startIndex + (segmentSize - 1) : _serverData.Count;
                GameObject item;
                // 往 svLeft.content 中添加服务器列表,实例化组件
                if (loginId > 0 && _currentRangeTuple.Item1 == startIndex)
                    item = Instantiate(Resources.Load<GameObject>("UI/Prefabs/ServerLeftSelectedItem"));
                else
                    item = Instantiate(Resources.Load<GameObject>("UI/Prefabs/ServerLeftItem"));


                // 
                // 设置成svLeft.content的子物体
                item.transform.SetParent(svLeft.content, false);
                var serverLeft = item.GetComponent<ServerLeftItem>();


                serverLeft.InitButtonText(new int[] {startIndex, endIndex}); // [startIndex, endIndex] 功能 'collection expressions' 不可用。请使用语言版本 12.0 或更高
            }
        }

        // 1.数据回显(之前缓存的数据)
        // 2.服务器列表初始化与状态数据回显(后台获取的数据)
        // 之前缓存的数据中有登录过的服务器ID,title服务器信息,依然需要根据列表匹配获取
        public override void ShowMe()
        {
            _serverData = LoginMgr.Instance.ServerData;

            base.ShowMe();
            // _lastChooseServerText 无
            // _lastServerStateImage setActive false
            // _serverRangeText 默认 1~5区
            // 获取上一次的登录数据
            loginId = LoginMgr.Instance.LoginData.lastServerId;
            if (loginId <= 0)
            {
                _lastChooseServerText.text = "无";
                _lastServerStateImage.gameObject.SetActive(false);
                // 1-5
            } else
            {
                // LoginMgr.Instance.ServerData 中,查询到对应的服务器信息
                var serverInfo = _serverData.Find(server => server.id == loginId);
                if (serverInfo != null)
                {
                    _lastChooseServerText.text = serverInfo.id + "区 " + serverInfo.name;
                    _lastServerStateImage.gameObject.SetActive(true);
                    // 获取 spriteAtlas
                    var spriteAtlas = Resources.Load<SpriteAtlas>("UI/SpriteAtlas/Login");
                    switch (serverInfo.state)
                    {
                        case 0:
                            _lastServerStateImage.gameObject.SetActive(false);
                            break;
                        case 1:
                            _lastServerStateImage.sprite = spriteAtlas.GetSprite("ui_DL_liuchang_01");
                            break;
                        case 2:
                            _lastServerStateImage.sprite = spriteAtlas.GetSprite("ui_DL_fanmang_01");
                            break;
                        case 3:
                            _lastServerStateImage.sprite = spriteAtlas.GetSprite("ui_DL_huobao_01");
                            break;
                        case 4:
                            _lastServerStateImage.sprite = spriteAtlas.GetSprite("ui_DL_weihu_01");
                            break;
                    }
                }

                var avgRangeList = IntervalSegmentation.SegmentInterval(_serverData.Count, segmentSize);
                var _segment = IntervalSegmentation.FindIntervalContainingValue(avgRangeList, loginId);
                _currentRangeTuple = _segment;
                UpdatePanel(_segment.Item1, _segment.Item2);
            }
        }

        // 清空 svRight.content 中的服务器列表
        private void clearServerRightItems()
        {
            for (var i = 0; i < _serverRightItems.Count; i++)
            {
                var item = _serverRightItems[i];
                if (item != null) Destroy(item);
            }

            _serverRightItems.Clear();
        }

        public void UpdatePanel(int beginIndex, int endIndex)
        {
            clearServerRightItems();
            // 更新服务器区间显示
            _serverRangeText.text = "服务器 " + beginIndex + "-" + endIndex;
            var segmentSize = endIndex - beginIndex + 1;
            var currentIdx = beginIndex - 1;
            // 往 svRight.content 中添加服务器列表
            for (var i = 0; i < segmentSize; i++)
            {
                var item = Instantiate(Resources.Load<GameObject>("UI/Prefabs/ServerRightItem"));
                item.transform.SetParent(svRight.content, false);
                var serverInfo = LoginMgr.Instance.ServerData[currentIdx];
                item.GetComponent<ServerRightItem>().ChangeInfo(serverInfo);
                _serverRightItems.Add(item);
                currentIdx++;
            }
        }
    }
}